package demo;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import bean.PollOption;
import bean.PollTopic;

/**
 * @author wanghao7@asiainfo-linkage.com
 * @created on Dec 5, 2012 3:24:13 PM
 * @version
 * @since jdk1.5
 * @description
 */
public class Test {
	public static void main(String[] args) {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("inheritance-jpa");
		EntityManager em = emf.createEntityManager();
		PollTopic pt = insertTest(em);
		em.persist(pt);
		em.flush();
		queryTest(em);
		em.getTransaction().commit();
		em.close();
	}

	private static void queryTest(EntityManager em) {
		Query query = em.createQuery("from PollTopic where 1 = :flag");
		query.setParameter("flag", 1);
		query.setFirstResult(0);
		query.setMaxResults(10);
		@SuppressWarnings("unchecked")
		List<PollTopic> results = query.getResultList();
		System.out.println("\n\n-----------\n");
		for (PollTopic topic : results) {
			System.out.println(topic.getTopicTitle());
			System.out.println(topic.getOptions());
		}
	}

	private static PollTopic insertTest(EntityManager em) {
		em.getTransaction().begin();
		PollTopic pt = new PollTopic();
		pt.setMaxChoices(4);
		pt.setTopicTime(new Date());

		Set<PollOption> options = new HashSet<PollOption>();

		PollOption po1 = new PollOption();
		PollOption po2 = new PollOption();

		po1.setOptionItem("po1");
		po2.setOptionItem("po2");

		po1.setPollTopic(pt);
		po2.setPollTopic(pt);

		options.add(po1);
		options.add(po2);

		// we can just set PollOption's pollTopic and persistence option
		// individual or just set options to pollTopic and the options will be
		// persistence auto
		pt.setOptions(options);
		return pt;
	}
}
